package org.vergil.utils;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则方法类
 *
 * @author: yuantao
 * @Date: 2018/4/22
 * @since 1.0.0
 */
public class RegexUtil {

    public final static String EMAIL = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
    public final static String YMD = "\\d{4}-\\d{2}-\\d{2}";
    public final static String MOBILE = "^[1][3,4,5,6,7,8,9][0-9]{9}$";
    public final static String PHONE = "^[1-9]{1}[0-9]{5,8}$";
    public final static String PHONE_AREA = "^[0][1-9]{2,3}-[0-9]{5,10}$";

    /**
     * @param str   要验证的字符串
     * @param regex 验证规则
     * @return
     */
    public static boolean checkRegex(String str, String regex) {
        // 编译正则表达式
        Pattern pattern = Pattern.compile(regex);
        // 忽略大小写的写法
        Matcher matcher = pattern.matcher(str);
        // 字符串是否与正则表达式相匹配
        return matcher.matches();
    }

    /**
     * 验证邮箱
     *
     * @param email
     * @return
     */
    public static boolean checkEmail(String email) {
        return checkRegex(email, EMAIL);
    }

    /**
     * 验证手机号码
     *
     * @param mobile
     * @return
     */
    public static boolean checkMobile(String mobile) {
        return checkRegex(mobile, MOBILE);
    }


    /**
     * 验证url
     *
     * @param urlStr
     * @return
     */
    public static boolean checkeURL(String urlStr) {
        try {
            URL url = new URL(urlStr);
            return true;
        } catch (MalformedURLException e) {
            return false;
        }
    }

    /**
     * 替换匹配字符
     *
     * @auther: yuantao
     * @date: 2018/5/13
     */
    public static String replace(String regex, String replaceStr, final String original) {
        String result = null;
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(original);
        return matcher.replaceAll(replaceStr);
    }

    /**
     * 获取匹配字符
     *
     * @auther: yuantao
     * @date: 2018/5/13
     */
    public static String getRegex(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
            return matcher.group();
        } else {
            return null;
        }
    }
}
